import React, { memo, useMemo } from 'react';
import { Rnd } from 'react-rnd';
import type { RndDragEvent, DraggableData, Position } from 'react-rnd';
import { ResizeDirection } from 're-resizable';
import DynamicEngine from '@/renderer/DynamicEngine';
import styles from './index.less';
import { PointDataItem } from '@/ui-components/common';
interface ViewRenderProps {
  canvasId: string;
  curPointId: string | undefined | null;
  pointDataItem: PointDataItem;
  onDragStop?: Function;
  onDragStart?: Function;
  onResizeStop?: Function;
}
const ViewRender = memo((props: ViewRenderProps) => {
  const {
    canvasId,
    curPointId,
    pointDataItem,
    onDragStop,
    onDragStart,
    onResizeStop,
  } = props;
  const { id, item, point } = pointDataItem;
  const { enableResizing } = item;
  const { w, h, x, y } = point;
  const dragStart = (point: any, e: RndDragEvent, data: DraggableData) => {
    onDragStart && onDragStart(point);
  };
  const dragStop = (point: any, e: RndDragEvent, data: DraggableData) => {
    const { x, y } = data;
    const newPoint = {
      ...point,
      x,
      y,
    };
    onDragStop && onDragStop(newPoint);
  };
  const resizeStop = (
    point: any,
    e: RndDragEvent,
    direction: ResizeDirection,
    ref: HTMLElement,
    delta: {
      height: number;
      width: number;
    },
    position: Position,
  ) => {
    const newPoint = {
      ...point,
      w: ref.offsetWidth,
      h: ref.offsetHeight,
      ...position,
    };
    onResizeStop && onResizeStop(newPoint);
  };
  return (
    <Rnd
      key={id}
      style={{
        display: 'flex',
        alignItems: 'center',
        justifyContent: 'center',
      }}
      className={`${styles.dragItem} ${
        curPointId === id && styles.activeDragItem
      }`}
      minWidth={32}
      minHeight={32}
      bounds={`#${canvasId}`}
      size={{
        width: w,
        height: h,
      }}
      position={{
        x,
        y,
      }}
      enableResizing={enableResizing}
      onDragStart={dragStart.bind(this, point)}
      onDragStop={dragStop.bind(this, point)}
      onResizeStop={resizeStop.bind(this, point)}
    >
      <DynamicEngine {...(item as any)} />
    </Rnd>
  );
});

export default ViewRender;
